/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package calculatorParser;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author konstantin
 */
public class Scanner {
    
    static public final String regexpForDouble = "-?\\d+(\\.\\d+)?";
    static public String[] tokens = {
        "\\(",
        "\\)",
        "\\+",
        "\\-",
        "\\*",
        "/",
        "sin",
        "cos",
        "ln",
        "exp",
        "sqrt",
        "dual",
        "pro",
        "inf",
        "sup",
        "opp",
        "inv",
        "\\[" + regexpForDouble + ";" + regexpForDouble + "\\]"
    };
    
    static public List<String> scanString(String expression) throws Exception {
        List<String> lexems = new LinkedList<String>();           
        expression = expression.replaceAll(" ", "");
        StringBuffer token = new StringBuffer(10);
        int offSet = 0;
        while (offSet <= expression.length() - 1) {
            token.append(expression.charAt(offSet));            
            for(String tokenRegExp: tokens) {
                Pattern valid = Pattern.compile(tokenRegExp);
                Matcher m = valid.matcher(token);
                boolean isValid = m.matches();
                if (isValid) {
                    lexems.add(token.toString());
                    token = new StringBuffer(10);
                    break;
                }
            }
            offSet++;
        }
        if (token.length() != 0) {
            throw new Exception("Лексическая ошибка!");
        }        
        return lexems;
    }
    
    public static void main(String[] args) {
        String exp = "([1;2] + [3; 4] + cos [5.36; -7.19] - sqrt ([16; 66] + [33;32] / [12; 73.33333]))";
        try {
            System.out.println(Scanner.scanString(exp));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}
